<template>
  <div class="script-importer">
    <div class="mb-3">
      <p class="text-xs text-gray-500 mb-2">脚本导入</p>
      
      <div class="grid grid-cols-3 gap-2">
        <!-- 保存按钮 -->
        <el-button 
          type="primary" 
          size="small"
          @click="saveScript"
          :disabled="!hasSteps"
        >
          <el-icon class="mr-1"><i-ep-upload /></el-icon>
          保存
        </el-button>

        <!-- 文件菜单 -->
        <el-dropdown @command="handleFileCommand" trigger="click">
          <el-button size="small">
            <el-icon class="mr-1"><i-ep-folder /></el-icon>
            文件
            <el-icon class="ml-1"><i-ep-arrow-down /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="import">
                <el-icon class="mr-2"><i-ep-upload /></el-icon>
                导入脚本
              </el-dropdown-item>
              <el-dropdown-item command="select-file">
                <el-icon class="mr-2"><i-ep-folder-opened /></el-icon>
                选择文件导入
              </el-dropdown-item>
              <el-dropdown-item command="export">
                <el-icon class="mr-2"><i-ep-download /></el-icon>
                导出脚本
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>

        <!-- 新步骤按钮 -->
        <el-button 
          size="small"
          @click="openNewStepModal"
        >
          <el-icon class="mr-1"><i-ep-plus /></el-icon>
          新步骤
        </el-button>
      </div>
    </div>

    <!-- 导入脚本模态框 -->
    <BaseModal
      v-model:visible="importModalVisible"
      title="导入自动化测试脚本"
      size="lg"
    >
      <template #header-actions>
        <el-dropdown @command="handleFormatCommand" trigger="click">
          <el-button size="small" text type="primary">
            <el-icon class="mr-1"><i-ep-refresh /></el-icon>
            转换格式
            <el-icon class="ml-1"><i-ep-arrow-down /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="playwright" :class="{ 'text-primary': currentFormat === 'playwright' }">
                <el-icon v-if="currentFormat === 'playwright'" class="mr-2"><i-ep-check /></el-icon>
                <span :class="{ 'ml-6': currentFormat !== 'playwright' }">Playwright</span>
              </el-dropdown-item>
              <el-dropdown-item command="jsonl" :class="{ 'text-primary': currentFormat === 'jsonl' }">
                <el-icon v-if="currentFormat === 'jsonl'" class="mr-2"><i-ep-check /></el-icon>
                <span :class="{ 'ml-6': currentFormat !== 'jsonl' }">JSONL</span>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </template>

      <div class="space-y-4">
        <!-- 脚本输入区域 -->
        <div>
          <div class="flex items-center justify-between mb-2">
            <label class="block text-sm font-medium text-gray-700">
              粘贴 {{ formatDisplay }} 脚本
            </label>
            <div class="text-xs text-primary">
              当前格式: {{ formatDisplay }}
            </div>
          </div>
          <el-input
            v-model="scriptContent"
            type="textarea"
            :rows="12"
            :placeholder="getPlaceholder()"
            class="font-mono text-sm"
          />
          <div class="flex justify-end mt-2">
            <el-button 
              size="small" 
              type="primary"
              @click="convertFormat"
              :disabled="!scriptContent.trim()"
            >
              <el-icon class="mr-1"><i-ep-refresh /></el-icon>
              一键转换格式
            </el-button>
          </div>
        </div>

        <!-- 分割线 -->
        <div class="flex items-center">
          <div class="flex-grow border-t border-gray-300"></div>
          <span class="mx-4 text-sm text-gray-500">或者</span>
          <div class="flex-grow border-t border-gray-300"></div>
        </div>

        <!-- 文件上传 -->
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">从文件导入</label>
          <div class="flex">
            <el-input
              v-model="selectedFileName"
              readonly
              placeholder="未选择文件"
              class="flex-1"
            />
            <el-button class="ml-2" @click="triggerFileSelect">
              <el-icon class="mr-1"><i-ep-folder-opened /></el-icon>
              浏览...
            </el-button>
          </div>
          <input
            ref="fileInput"
            type="file"
            accept=".js,.ts,.jsonl,.json,.py"
            class="hidden"
            @change="handleFileSelect"
          />
          <p class="mt-1 text-xs text-gray-500">
            支持的文件格式: .js, .ts, .jsonl, .json, .py
          </p>
        </div>
      </div>

      <template #footer>
        <el-button @click="importModalVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="confirmImport"
          :disabled="!scriptContent.trim() && !selectedFile"
        >
          导入
        </el-button>
      </template>
    </BaseModal>

    <!-- 导出脚本模态框 -->
    <BaseModal
      v-model:visible="exportModalVisible"
      title="导出自动化测试脚本"
      size="lg"
    >
      <div class="space-y-4">
        <!-- 脚本名称 -->
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">脚本名称</label>
          <el-input v-model="exportScriptName" placeholder="login_test" />
        </div>

        <!-- 导出格式 -->
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">导出格式</label>
          <div class="grid grid-cols-2 gap-3">
            <div 
              class="export-format-card"
              :class="{ active: exportFormat === 'playwright' }"
              @click="exportFormat = 'playwright'"
            >
              <div class="flex items-center">
                <div class="radio-button" :class="{ active: exportFormat === 'playwright' }"></div>
                <span class="ml-2 text-sm font-medium">Playwright</span>
              </div>
              <p class="text-xs text-gray-500 mt-1">JavaScript 格式的 Playwright 测试脚本</p>
            </div>
            <div 
              class="export-format-card"
              :class="{ active: exportFormat === 'jsonl' }"
              @click="exportFormat = 'jsonl'"
            >
              <div class="flex items-center">
                <div class="radio-button" :class="{ active: exportFormat === 'jsonl' }"></div>
                <span class="ml-2 text-sm font-medium">JSONL</span>
              </div>
              <p class="text-xs text-gray-500 mt-1">每行一个 JSON 对象的格式</p>
            </div>
          </div>
        </div>

        <!-- 导出选项 -->
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-2">导出选项</label>
          <div class="space-y-2">
            <el-checkbox v-model="exportOptions.includeComments">包含注释</el-checkbox>
            <el-checkbox v-model="exportOptions.includeScreenshots">包含截图步骤</el-checkbox>
            <el-checkbox v-model="exportOptions.prettyFormat">美化代码格式</el-checkbox>
          </div>
        </div>

        <!-- 预览 -->
        <div class="border border-gray-200 rounded-md p-4 bg-gray-50">
          <div class="flex items-center justify-between mb-2">
            <span class="text-sm font-medium text-gray-700">预览</span>
            <el-button size="small" text type="primary" @click="copyToClipboard">
              <el-icon class="mr-1"><i-ep-document-copy /></el-icon>
              复制代码
            </el-button>
          </div>
          <pre class="text-xs font-mono bg-gray-100 p-3 rounded-md max-h-32 overflow-auto">{{ exportPreview }}</pre>
        </div>
      </div>

      <template #footer>
        <el-button @click="exportModalVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmExport">导出</el-button>
      </template>
    </BaseModal>

    <!-- 隐藏的文件输入 -->
    <input
      ref="fileInput"
      type="file"
      accept=".js,.ts,.jsonl,.json,.py"
      class="hidden"
      @change="handleFileSelect"
    />
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useScriptStore } from '../stores/script'
import { ElMessage } from 'element-plus'
import BaseModal from './BaseModal.vue'

// Element Plus 图标
import {
  Upload as iEpUpload,
  Folder as iEpFolder,
  ArrowDown as iEpArrowDown,
  Plus as iEpPlus,
  FolderOpened as iEpFolderOpened,
  Download as iEpDownload,
  Refresh as iEpRefresh,
  Check as iEpCheck,
  DocumentCopy as iEpDocumentCopy,
  Aim as iEpAim
} from '@element-plus/icons-vue'

const scriptStore = useScriptStore()

// 响应式数据
const importModalVisible = ref(false)
const exportModalVisible = ref(false)
const scriptContent = ref('')
const currentFormat = ref('playwright')
const selectedFile = ref(null)
const selectedFileName = ref('')
const fileInput = ref(null)

// 导出相关
const exportFormat = ref('playwright')
const exportScriptName = ref('login_test')
const exportOptions = ref({
  includeComments: true,
  includeScreenshots: false,
  prettyFormat: true
})

// 计算属性
const hasSteps = computed(() => scriptStore.hasSteps)
const formatDisplay = computed(() => currentFormat.value === 'playwright' ? 'Playwright' : 'JSONL')

const exportPreview = computed(() => {
  if (scriptStore.steps.length === 0) {
    return '// 暂无步骤可导出'
  }
  return scriptStore.exportScript(exportFormat.value) || '// 导出预览'
})

// 方法
const handleFileCommand = (command) => {
  switch (command) {
    case 'import':
      openImportModal()
      break
    case 'select-file':
      triggerFileSelect()
      break
    case 'export':
      openExportModal()
      break
  }
}

const handleFormatCommand = (format) => {
  currentFormat.value = format
}

const openImportModal = () => {
  importModalVisible.value = true
  scriptContent.value = ''
  selectedFile.value = null
  selectedFileName.value = ''
}

const openExportModal = () => {
  if (!hasSteps.value) {
    ElMessage.warning('没有步骤可导出')
    return
  }
  exportModalVisible.value = true
}

const openNewStepModal = () => {
  // TODO: 实现新步骤模态框
  ElMessage.info('新步骤功能待实现')
}

const triggerFileSelect = () => {
  fileInput.value?.click()
}

const handleFileSelect = (event) => {
  const file = event.target.files[0]
  if (file) {
    selectedFile.value = file
    selectedFileName.value = file.name
    
    // 自动读取文件内容
    const reader = new FileReader()
    reader.onload = (e) => {
      scriptContent.value = e.target.result
      
      // 根据文件扩展名设置格式
      if (file.name.endsWith('.jsonl') || file.name.endsWith('.json')) {
        currentFormat.value = 'jsonl'
      } else {
        currentFormat.value = 'playwright'
      }
    }
    reader.readAsText(file)
  }
}

const getPlaceholder = () => {
  if (currentFormat.value === 'playwright') {
    return `import { test, expect } from '@playwright/test';

test('test', async ({ page }) => {
  // 在此粘贴您的 Playwright 脚本
  await page.goto('https://example.com');
  await page.fill('#username', 'admin');
  await page.click('#login-button');
});`
  } else {
    return `{"stepNumber":1,"type":"navigation","action":"goto","url":"https://example.com"}
{"stepNumber":2,"type":"input","action":"fill","selector":"#username","value":"admin"}
{"stepNumber":3,"type":"click","action":"click","selector":"#login-button"}`
  }
}

const convertFormat = () => {
  if (!scriptContent.value.trim()) {
    ElMessage.warning('请先输入脚本内容')
    return
  }
  
  try {
    // 解析当前脚本
    const result = scriptStore.importScript(scriptContent.value, currentFormat.value)
    if (result.success) {
      // 切换格式并导出
      const newFormat = currentFormat.value === 'playwright' ? 'jsonl' : 'playwright'
      const convertedScript = scriptStore.exportScript(newFormat)
      
      scriptContent.value = convertedScript
      currentFormat.value = newFormat
      
      ElMessage.success(`已转换为 ${newFormat === 'playwright' ? 'Playwright' : 'JSONL'} 格式`)
    } else {
      ElMessage.error(result.message || '转换失败')
    }
  } catch (error) {
    ElMessage.error('转换失败: ' + error.message)
  }
}

const confirmImport = () => {
  if (!scriptContent.value.trim()) {
    ElMessage.warning('请输入脚本内容')
    return
  }
  
  try {
    const result = scriptStore.importScript(scriptContent.value, currentFormat.value)
    if (result.success) {
      ElMessage.success(`成功导入 ${scriptStore.stepCount} 个步骤`)
      importModalVisible.value = false
    } else {
      ElMessage.error(result.message || '导入失败')
    }
  } catch (error) {
    ElMessage.error('导入失败: ' + error.message)
  }
}

const confirmExport = () => {
  try {
    scriptStore.scriptName = exportScriptName.value
    const exportedScript = scriptStore.exportScript(exportFormat.value)
    
    // 创建下载
    const blob = new Blob([exportedScript], { type: 'text/plain' })
    const url = URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `${exportScriptName.value}.${exportFormat.value === 'playwright' ? 'js' : 'jsonl'}`
    link.click()
    URL.revokeObjectURL(url)
    
    ElMessage.success('脚本导出成功')
    exportModalVisible.value = false
  } catch (error) {
    ElMessage.error('导出失败: ' + error.message)
  }
}

const copyToClipboard = async () => {
  try {
    await navigator.clipboard.writeText(exportPreview.value)
    ElMessage.success('代码已复制到剪贴板')
  } catch (error) {
    ElMessage.error('复制失败')
  }
}

const saveScript = () => {
  // TODO: 实现保存功能
  ElMessage.info('保存功能待实现')
}
</script>

<style scoped>
.export-format-card {
  @apply border border-gray-200 rounded-md p-3 cursor-pointer transition-all duration-200 hover:border-primary hover:bg-blue-50;
}

.export-format-card.active {
  @apply border-primary bg-blue-50;
}

.radio-button {
  @apply w-4 h-4 rounded-full border-2 border-gray-300 flex items-center justify-center;
}

.radio-button.active {
  @apply border-primary;
}

.radio-button.active::after {
  content: '';
  @apply w-2 h-2 bg-primary rounded-full;
}
</style>
